package com.changjiang.luban.utils.data;

import com.changjiang.luban.utils.ContrastUtils;
import lombok.Data;

import java.io.Serializable;
import java.util.List;

/**
 * Page
 * Description:基础分页类
 *
 * @author nichangjiang@vip.qq.com
 * @version v0.1
 * @date 2018/6/9 - 16:15
 */
@Data
public class Page<T> implements Serializable {

    /** 初始页码 */
    public static final int INIT_INDEX = 1;


    /** 初始页面大小*/
    public static final int INIT_SIZE = 10;

    /**  显示页码条目数，即页码数量顶多是10个 */
    private final static int PAGE_ITEM_COUNT = 10;
    /**
     * 当前页码
     */
    private Integer index;

    /**
     * 当前页码
     */
    private Integer size=INIT_SIZE;

    /**
     * 总数据行数
     */
    private Integer rowCount;

    /**
     * 总页码数
     */
    private Integer pageCount;

    /**
     * 数据
     */
    private List<T> rowList;

    /**
     * 前一页
     */
    private int previousPage;

    /**
     * 下一页
     */
    private int nextPage;

    /**
     * 第一页
     */
    private int firstPage = 1;

    /**
     * 最后一页
     */
    private int lastPage;

    /**
     * 页码
     */
    private int[] numbers;

    /**
     * 请求地址
     */
    private String linkUrl;

    public Page() {
    }

    public Page(Integer index, Integer size, String linkUrl) {
        this.index = index;
        this.linkUrl = linkUrl;
        if(ContrastUtils.isZero(size)){
            this.size = Page.INIT_SIZE;
        }else{
            this.size = size;
        }
    }

    public void setRowList(List<T> rowList) {
        this.rowList = rowList;
        //计算数据的总页数
        this.pageCount =  rowCount % size != 0 ? rowCount / size + 1 : rowCount / size;
    }

    public int[] getPageBar() {
        int startPage;
        int endPage;
        int pageBar[] = null;
        //当总页码不足或等于既定页面大小时
        if(this.getPageCount() <= PAGE_ITEM_COUNT){
            pageBar = new int[this.pageCount];
            startPage = 1;
            endPage = this.pageCount;
        }else{                  //当总页码大于既定页面大小时
            pageBar = new int[PAGE_ITEM_COUNT];
            startPage = this.index - (PAGE_ITEM_COUNT/2-1);
            endPage = this.index + PAGE_ITEM_COUNT/2;

            if(startPage<1){
                startPage = 1;
                endPage = PAGE_ITEM_COUNT;
            }

            if(endPage>this.pageCount){
                endPage = this.pageCount;
                startPage = this.pageCount - (PAGE_ITEM_COUNT-1);
            }
        }

        int index = 0;
        for(int i=startPage;i<=endPage;i++){
            pageBar[index++] = i;
        }

        this.numbers = pageBar;
        return this.numbers;
    }
}
